import {createStore} from 'vuex'

const STORAGE_KEY="todos-vuejs"
const localStoragePlugin = (store) => {
    store.subscribe((mutation, {todos}) => {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
    })
}

const state = createStore({
    state() {
        return {
            todos: JSON.parse(localStorage.getItem(STORAGE_KEY)) || []
        }
    },
    getters: {
        todos: state => state.todos
    },
    mutations: {
        addTodo(state, text) {
            state.todos.push({text, done: false})
        },
        deleteTodo(state, index) {
            state.todos.splice(index, 1)
        },
        toggleTodo(state, index) {
            state.todos[index].done = !state.todos[index].done
        }
    },
    plugins: [localStoragePlugin]
})

export default state
